import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

// 获取问题列表
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { searchParams } = new URL(req.url)
    const experimentId = searchParams.get('experimentId')
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '10')
    const skip = (page - 1) * limit

    // 构建查询条件
    const where: any = {}
    if (experimentId) {
      where.experimentId = experimentId
    }

    // 获取问题列表
    const questions = await prisma.forumQuestion.findMany({
      where,
      include: {
        author: {
          select: {
            id: true,
            name: true,
            role: true,
          },
        },
        experiment: {
          select: {
            id: true,
            title: true,
          },
        },
        _count: {
          select: {
            answers: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
      skip,
      take: limit,
    })

    // 获取总数
    const total = await prisma.forumQuestion.count({ where })

    return NextResponse.json({
      questions,
      pagination: {
        total,
        page,
        limit,
        pages: Math.ceil(total / limit),
      },
    })
  } catch (error) {
    console.error('获取问题列表失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
}

// 创建问题
export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { title, content, experimentId } = await req.json()

    // 验证输入
    if (!title || !content || !experimentId) {
      return NextResponse.json(
        { message: '缺少必要参数' },
        { status: 400 }
      )
    }

    // 检查实验是否存在
    const experiment = await prisma.experiment.findUnique({
      where: { id: experimentId },
    })

    if (!experiment) {
      return NextResponse.json(
        { message: '实验不存在' },
        { status: 404 }
      )
    }

    // 创建问题
    const question = await prisma.forumQuestion.create({
      data: {
        title,
        content,
        authorId: session.user.id,
        experimentId,
      },
      include: {
        author: {
          select: {
            id: true,
            name: true,
            role: true,
          },
        },
        experiment: {
          select: {
            id: true,
            title: true,
          },
        },
      },
    })

    return NextResponse.json({
      message: '问题创建成功',
      question,
    }, { status: 201 })
  } catch (error) {
    console.error('创建问题失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
} 